<template>
  <div class="topBar">
    <div>
      <img src="../assets/在线人数标识.png" />
      <span style="margin-left: 1rem">{{ duration }}</span>
      <span style="margin-left: 1rem">课堂人数：{{ numberOfMember }}</span>
    </div>
    <span class="centerSpan">课程名：{{ roomName }}</span>
  </div>
  <div class="bottonBar">
    <div class="centerBottom">
      <div class="button" @click="controlMicrophone()">
        <img src="../assets/class/麦克风.png" v-if="microphone.microphoneOn">
        <img src="../assets/class/麦克风关.png" v-if="microphone.microphoneOff">
        <span>麦克风</span>
      </div>
      <div class="button" @click="controlVideo()">
        <img src="../assets/class/视频.png" v-if="video.videoOn">
        <img src="../assets/class/关闭视频.png" v-if="video.videoOff">
        <span>视频</span>
      </div>
      <div class="button">
        <img src="../assets/class/签到.png" @click="startSignUp()">
        <span>签到</span>
      </div>
      <div class="button">
        <img src="../assets/class/邀请.png" @click="inviteOther()">
        <span>邀请</span>
      </div>
      <div class="button" @click="shareScreen()">
        <img src="../assets/屏幕共享.png" style="width: 2rem;">
        <span>共享</span>
      </div>
      <div class="button" @click="startChat()">
        <img src="../assets/class/聊天.png" style="width: 2rem;">
        <span>聊天</span>
      </div>
      <div class="button" @click="startRecord()">
        <img src="../assets/class/录制.png" style="width: 2rem;">
        <span>录制</span>
      </div>
      <div class="button" @click="popSetting1()">
        <img src="../assets/class/设置.png">
        <span>设置</span>
      </div>
    </div>
  </div>
  <blackboard ref="blackboardComponent" />
  <setting ref="popSetting" />
  <alert-box ref="alert" />
  <invite-member ref="invite" />
  <chat ref="chatBox" />
  <signUp ref="signBox" />
  <videoSidebar ref="videoBar" />
  <record ref="recordBox" />
  <messageBox ref="message" />
</template>

<script setup>
import signUp from './../components/class/signUp.vue'
import chat from './../components/class/chat.vue'
import store from "@/store";
import { inject, onMounted, onUnmounted, reactive, ref } from "vue";
import blackboard from "@/components/blackboard.vue";
import setting from "@/components/setting.vue";
import inviteMember from '@/components/class/inviteMember'
import { useWebsocket } from "../hooks";
import router from '@/router';

const roomName = ref(store.state.roomData.roomName);
const blackboardComponent = ref(null);
const popSetting = ref(null)  //弹出设置
const alert = ref(null) //弹出框
const invite = ref(null)  //邀请成员
const duration = ref('0min')  //上课时间
const numberOfMember = ref(1) //成员数
const socket = useWebsocket(handelMessage); //连接socket
const chatBox = ref(null)
const signBox = ref(null)
const recordBox = ref(null)
const message = ref(null)

onMounted(() => {
  blackboardComponent.value.changeBackgroundColor();
  getTime();
  //刷新之后踹回主页去
  if (userId == 123456789) {
    router.push('/login')
  }
});

onUnmounted(() => {
  leaveClass(); //减少课堂人数
  socket.close()  //关闭socket，减少失败消息弹出的次数
})

//获取进入会议的时间
//这段代码有bug，零点过后显示的时间会变成负数，虽然没什么影响就是了
var recentTime;
var recentHour;
var recentMinutes;
function getTime() {
  const startTime = new Date();
  setInterval(() => {
    recentTime = new Date();
    var recentHour = recentTime.getHours() - startTime.getHours();
    var recentMinutes = recentTime.getMinutes() - startTime.getMinutes();
    duration.value =
      recentHour == 0
        ? recentMinutes + "min"
        : recentHour + "h" + recentMinutes + "min";
  }, 1000 * 60);
  //在mounted函数中无法使用，无奈只能把加人数的代码写在这里
  setTimeout(() => {
    getMember();

    //检查socket连接状态的代码也是这样
    // console.log('socket状态', store.state.socketState)
    if (!store.state.socketState) {
      setTimeout(() => {
        alert.value.alertContent = 'WebSocket连接失败！请检查网络设置并重启页面！'
        alert.value.showAlert();
      }, 2000)
    }
  }, 2000)
}

//开启聊天页面
function startChat() {
  chatBox.value.handleExit();
}

//开启录制页面 
function startRecord() {
  recordBox.value.showRecord();
}

//开关麦克风
const microphone = reactive({
  microphoneOn: true,
  microphoneOff: false
})
function controlMicrophone() {
  microphone.microphoneOn = !microphone.microphoneOn
  microphone.microphoneOff = !microphone.microphoneOff
}

//开关视频
const video = reactive({
  videoOn: true,
  videoOff: false
})
function controlVideo() {
  video.videoOn = !video.videoOn
  video.videoOff = !video.videoOff
}

//统计入会人数
const userId = store.state.userData.userId
const roomId = store.state.roomData.roomId
function getMember() {
  //向socket发送信息
  socket.send(JSON.stringify({
    userId: userId,
    roomId: roomId,
    userName: store.state.userData.username,
    numberOfMember: numberOfMember.value,
    type: 'joinClass'
  }))
  message.value.receiveMessage(store.state.userData.username + ' 已加入课堂')
}

//离开课堂减少课堂人数
function leaveClass() {
  //向socket发送信息
  socket.send(JSON.stringify({
    userId: userId,
    roomId: roomId,
    numberOfMember: numberOfMember.value,
    type: 'leaveClass'
  }))
}

//接收socket信息
function handelMessage(event) {
  const data = JSON.parse(event.data);
  //防止用户重复收到消息
  if (userId == data.userId) {
    if (data.type == 'newNumber') {
      numberOfMember.value = data.numberOfMember + 1
    } else if (data.type == "message") {
      message.value.receiveMessage(data.userName + '：' + data.msg);
    }
    return;
  }
  // console.log('socket发送的' + data.type, data);
  switch (data.type) {
    case 'joinClass':
      numberOfMember.value = data.numberOfMember + 1
      console.log(numberOfMember.value)
      socket.send(JSON.stringify({
        userId: userId,
        roomId: roomId,
        type: 'updateNumber'
      }))
      message.value.receiveMessage(data.userName + ' 已加入课堂')
      break;
    case 'updateNumber':
      socket.send(JSON.stringify({
        userId: userId,
        roomId: roomId,
        type: 'newNumber',
        numberOfMember: numberOfMember.value
      }))
      break;
    case 'leaveClass':
      numberOfMember.value = data.numberOfMember - 1
      console.log(numberOfMember.value)
      socket.send(JSON.stringify({
        userId: userId,
        roomId: roomId,
        type: 'updateNumber'
      }))
      break;
    case "message": //显示消息 
      message.value.receiveMessage(data.userName + '：' + data.msg);
      break;
  }
  console.log('课堂人数：', numberOfMember.value)
}

//显示设置
function popSetting1() {
  popSetting.value.popOutSetting();
}

//设置签到
function startSignUp() {
  signBox.value.showSignUp();
}

//邀请成员
function inviteOther() {
  invite.value.handleExit();
  try {
    invite.value.copyContent();
  } catch (error) {
    alert.value.alertContent = '复制邀请内容失败！'
    alert.value.showAlert();
    return;
  }
  alert.value.alertContent = '复制邀请内容成功！'
  alert.value.showAlert();
}

//屏幕共享
const stream = ref();
async function shareScreen() {
  try {
    stream.value = await navigator.mediaDevices.getDisplayMedia({ video: true });
  } catch (err) {
    console.error("Error: " + err);
    alert.value.alertContent = '获取屏幕信息失败！'
    alert.value.showAlert();
  }
}
</script>

<style scoped>
.topBar {
  background-color: #ffffff;
  height: 5rem;
  width: 100%;
  position: absolute;
  top: 0px;
  left: 0px;
  border-bottom: rgb(224, 224, 224) solid 1px;
  z-index: 100;
  pointer-events: none;
}

.topBar div {
  position: absolute;
  top: 1.5rem;
  left: 2.75rem;
  display: flex;
  align-items: center;
  color: #33df81;
}

.centerSpan {
  color: black;
  position: absolute;
  top: 2.5rem;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 1.5rem;
}

.bottonBar {
  background-color: #ffffff;
  height: 6.75rem;
  width: 100%;
  position: absolute;
  bottom: 0px;
  left: 0px;
  border-top: rgb(224, 224, 224) solid 1px;
  z-index: 99;
}

.centerBottom {
  position: absolute;
  left: 50%;
  bottom: 0px;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  width: auto;
  height: auto;
}

.button {
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 3rem;
  height: auto;
  margin: 5px 5px 0px 5px;
}

.button img {
  height: 2rem;
  width: auto;
}

span {
  margin-top: 4px;
  font-size: 1rem;
}
</style>
